<?php
namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use yii\data\Pagination;
use backend\models\system\SysConfig;
use frontend\models\question\Course;
use frontend\models\question\Ques;
use frontend\models\question\Question;
use frontend\models\question\Queslabel;
use frontend\models\question\Questionlabel;
use frontend\models\question\Answer;
use frontend\models\operate\User;
use backend\models\Collection;
	/**	
	 * @inheritdoc	模块：有问必答
	 * @author Yang Zhang
	 */
header("content-type:text/html;charset=utf-8");
class QuestionsController extends Controller
{
	public $enableCsrfValidation = false;
	/**
	 * @inderitdoc 验证码配置
	 */
	public function actions()
	{
		return [
			'captcha'=>[
				'class'=>'yii\captcha\CaptchaAction',
				'maxLength'=>5,
				'minLength'=>5,
			],
		];
	}
	/**
	 * @inheritdoc 公共部分
	 */

	public function common()
	{
		$model = new Question;
		$label = $model->labels();
		/*设置显示数量*/
		$num = 5;
		$hot = $model->HotIssure($num);
		/*注意设置*/
		$notice = SysConfig::find()->where("config_type=20")->asarray()->all();
		return ['hot'=>$hot,'label'=>$label,'notice'=>$notice];
	}
	/**
	 *  @inheritdoc 问答 最新 最热
	 */
	public function actionIndex()
	{
		$action = Yii::$app->request->get('action');
		if($action=='hot'){
			$orderby = " ques_answersum desc ";
		}elseif($action=='new'){
			$orderby = " ques_addtime desc ";
		}else{
			$orderby = " ques_addtime desc ";
		}
		
		$pages = new Pagination([
				'defaultPageSize'=>5,
				'totalCount' =>Question::find()->where("ques_type=0 and ques_answersum!=0")->count(),
			]);
		$model = new Question;
		$data = $model->Ques($pages,$orderby);
		/**/
		foreach ($data as $key => $answer) {
			$ques_id = $answer['ques_id'];
			$answers = Answer::find()->where("ques_id = $ques_id")->orderby("answer_addtime desc")->asarray()->one();
			$data[$key]['answers'] = $answers;
		}
		return $this->render('index',[
				"name"=>$data,
				'pages'=>$pages,
			]);
	}

	/**
	 * @inheritdoc 
	 */
	public function actionCount()
	{
		$ques_id = yii::$app->request->post("ques_id");
		$model = new Question;
		$data = $model->Prodetails($ques_id);
		$count = Ques::findOne($ques_id);
        $num = $data['ques_viewsum']+1;
        $count->ques_viewsum =$num;
        $count->save();
	}
	/**
	 * @inderitdoc 问答详情页
	 */
	public function actionDetails()
	{
		$ques_id = Yii::$app->request->get("ques_id");
		$model = new Question;
		$data = $model->Prodetails($ques_id);
		$release = Answer::find()
				->select("*")
				->innerjoin("edu_user","edu_answer.user_id=edu_user.user_id")
				->where("edu_answer.ques_id = $ques_id")->orderby("edu_answer.answer_addtime desc")->limit(5)->asarray()->all();	
		return $this->render('details',['model'=>$model,'data'=>$data,'release'=>$release]);
	}

	/**
	 * @inheritdoc 问答回复
	 */
	public function actionReply()
	{
		$ques_id = yii::$app->request->post("ques_id");
		$session = Yii::$app->session;
		$user_id = $session->get('user_id');
		if(empty($user_id))
	    {
	        $this->redirect(array('/site/index')); 
	    }  	
		$db = User::find()->where(['user_id'=>$user_id])->asarray()->one();
        $user_name = $db['user_name'];
        $data = Ques::find()->where(['ques_id'=>$ques_id])->asarray()->one();
		$str = Yii::$app->request->post("answer_content");
		/*$sql = "SELECT find,replacement from edu_Illegal WHERE instr($str,find)";*/
		/*$str = "我估算UI妮哦AV12次下跪拉萨路54式空间里看见爱上的女1夜情";*/
		if(empty($str))
		{
			echo "<script>alert('内容不能为空');location.href='details?ques_id=$ques_id'</script>";die;
		}
		$arr = new Answer;
		$arr = $arr->ReplyAdd($str);
		foreach ($arr as $key => $val) 
		{
			$error = $val['find'];
			$replace = $val['replacement'];	
			$info = preg_replace("/$error/",$replace,$str);
			$str=$info;		
		}
		$model = new Answer;
		$model->user_id 		= $user_id;
		$model->ques_id     	= $ques_id;
		$model->answer_addtime = time();
		$model->answer_content	= $str;
		$rs = $model->save();
		$new = Ques::findOne($ques_id);
		$num = $data['ques_answersum']+1;
		$new->ques_answersum = $num;
		$news = $new->save();
		if($rs && $news){
			echo "<script>alert('评论成功');location.href='details?ques_id=$ques_id'</script>";
		}else{
			echo "<script>alert('评论失败');location.href='details?ques_id=$ques_id'</script>";
		}

	}
	/**
	 * @inderitdoc 等待回复
	 */
	public function actionWaiting()
	{
		$action = Yii::$app->request->get('action');
		$type = "ques_answersum=0";
		$pages = new Pagination([
				'defaultPageSize'=>5,
				'totalCount' =>Question::find()->where($type)->count(),
			]);
		$model = new Question;
		$data = $model->Wait($pages,$type);
		return $this->render('waiting',[
				"name"=>$data,
				'pages'=>$pages,
				'answer'=>$answers
			]);
	}
	
	/**
	 * @inheritdoc 课程问答
	 */
	public function actionCourse()
	{
		$action = Yii::$app->request->get('action');
		$type = "ques_type=1";
		$pages = new Pagination([
				'defaultPageSize'=>5,
				'totalCount' =>Question::find()->where($type)->count(),
			]);
		$model = new Question;
		$data = $model->Wait($pages,$type);
		if(!empty($data))
		{
			foreach ($data as $key => $answer) {
				$ques_id[] = $answer['ques_id'];
			}
			$ques_id = implode(',', $ques_id);
			$answers = Answer::find()->where("ques_id in ($ques_id)")->asarray()->all();
			foreach ($answers as $kk => $val) {
				if($val['answer_best']!=1)
				{
					unset($answers[$kk]);
				}
			}
		}
		
		return $this->render('course',[
				"name"=>$data,
				'pages'=>$pages,
				'answer'=>$answers
			]);
	}
	/**
	 * @inheritdoc  标签搜索问题
	 */
	public function actionLabsearch()
	{
		$label_id = Yii::$app->request->get('label_id');
		if(!empty($label_id))
		{
			$model = new Question;
			$pages = new Pagination([
				'defaultPageSize'=>5,
				'totalCount' =>$model->CountSum($label_id),
			]); 
			$data = $model->LabelSearch($pages,$label_id);
			
			foreach ($data as $key => $answer) {
				$ques_id[] = $answer['ques_id'];
			}
			$ques_id = implode(',', $ques_id);
			$answers = Answer::find()->where("ques_id in ($ques_id)")->asarray()->all();
			
			return $this->render('index',[
					"name"=>$data,
					'pages'=>$pages,
					'answer'=>$answers
				]);
		}
		else
		{
			echo "<script>alert('非法操作');location.herf='index.php/questions/index'</script>";
		}
	}
	/**
	 * @inheritdoc 发布问题
	 */
	public function actionRelease()
	{
		if(!\Yii::$app->request->post())
		{
			$model = new Question;
			$labels = $model->labels();
			return $this->render('release',['model'=>$model,'labels'=>$labels]);
		}
		else
		{
			$session = yii::$app->session;
			$user_id = $session->get("user_id");
			$db = User::find()->where(['user_id'=>$user_id])->asarray()->one();
        	$user_name = $db['user_name'];
			$info = yii::$app->request->post();
			$model = new Ques;
			$model->ques_name 		= $info['title'];
			$model->ques_content 	= $info['editorValue'];
			$model->ques_addtime	= time();
			$model->user_id			= $user_id;
			$model->user_name		= $user_name;
			$rs = $model->save();
			$last_id = Yii::$app->db->getLastInsertID();
			$label_id = $info['label_id'];
			$label_id = explode(',', $label_id);
			foreach ($label_id as $key => $val) {
				$label = new Queslabel;
				$label->queslabel_id = $val;
				$label->ques_id 		= $last_id;
				$label->save();
			}			
			if($rs)
			{
				echo "<script>alert('发布成功');location.href='index'</script>";
			}
			else
			{
				echo "<script>alert('发布失败');location.href='release'</script>";
			}
		}
		


	}

	/**
	 * @inheritdoc 收藏
	 */
	public function actionCollect()
	{
		$session = Yii::$app->session;
		$user_id = $session->get('user_id');
		$request = Yii::$app->request->get();
		$id = $request['id'];
		if($user_id){
			$collection = new Collection;
			$data = $collection -> collect($user_id,$id,3);
			if($data){
				return json_encode([
					'code' => 2,
					'msg'  => '您已收藏！',
				]);die;
			}else{
				$collection -> user_id = $user_id;
				$collection -> collect_type = 3;
				$collection -> model_id = $id;
				$collection -> collect_addtime = time();
				$res = $collection -> save();
				if($res){
					return json_encode([
						'code' => 3,
						'msg'  => '收藏成功',
					]);die;
				}else{
					return json_encode([
						'code' => 4,
						'msg'  => '收藏失败',
					]);die;
				}
			}
		}else{
			return json_encode([
					'code' => 1,
					'msg'  => '请先登录！',
				]);die;
		}
	}
}
?>